import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('auth_token') || null,
    isAuthenticated: !!localStorage.getItem('auth_token'),
    loading: false,
    error: null
  }),

  getters: {
    isLoggedIn: (state) => state.isAuthenticated && state.token,
    currentUser: (state) => state.user,
    username: (state) => state.user?.username || localStorage.getItem('username'),
    userRole: (state) => state.user?.role || localStorage.getItem('user_role'),
    isAdmin: (state) => {
      const role = state.user?.role || localStorage.getItem('user_role')
      return role === 'ADMIN'
    },
    isUser: (state) => {
      const role = state.user?.role || localStorage.getItem('user_role')
      return role === 'USER'
    }
  },

  actions: {
    async login(credentials) {
      try {
        this.loading = true
        this.error = null
        
        const response = await authAPI.login(credentials)
        const { token, username, role } = response.data
        
        this.token = token
        this.isAuthenticated = true
        this.user = { username, role }
        
        localStorage.setItem('auth_token', token)
        localStorage.setItem('username', username)
        localStorage.setItem('user_role', role)
        
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    async register(userData) {
      try {
        this.loading = true
        this.error = null
        
        const response = await authAPI.register(userData)
        const { token, username, role } = response.data
        
        this.token = token
        this.isAuthenticated = true
        this.user = { username, role }
        
        localStorage.setItem('auth_token', token)
        localStorage.setItem('username', username)
        localStorage.setItem('user_role', role)
        
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    async getCurrentUser() {
      try {
        const response = await authAPI.getCurrentUser()
        this.user = response.data
        return response.data
      } catch (error) {
        this.logout()
        throw error
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      this.error = null
      
      localStorage.removeItem('auth_token')
      localStorage.removeItem('username')
      localStorage.removeItem('user_role')
    },

    clearError() {
      this.error = null
    }
  }
})